package com.luych.toolbox.base.service.controller;

import com.luych.toolbox.base.service.entity.Task;
import com.luych.toolbox.base.service.service.TaskService;
import com.luych.toolbox.common.enums.TaskStatus;
import com.luych.toolbox.common.feign.intf.base.service.TaskFeign;
import com.luych.toolbox.common.feign.param.base.service.TaskParam;
import com.luych.toolbox.common.feign.view.base.service.TaskView;
import com.luych.toolbox.common.page.CommonPageParam;
import com.luych.toolbox.common.page.CommonSort;
import com.luych.toolbox.common.page.PageResult;
import com.luych.toolbox.common.service.base.BaseController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "任务")
@RestController
@RequestMapping("/task")
public class TaskController
        extends BaseController<TaskView, TaskParam, Task>
        implements TaskFeign {

    private final TaskService taskService;

    @Autowired
    public TaskController(TaskService taskService) {
        super(taskService);
        this.taskService = taskService;
    }

    @Override
    public TaskPageResult pageByKeyword(long pageSize, long pageNumber, String sort, String order, String keyword, TaskStatus status) {
        CommonPageParam commonPageParam = CommonPageParam.getInstance().setPageSize(pageSize).setPageNumber(pageNumber);
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            commonPageParam.addSort(CommonSort.getInstance().setSort(sort).setOrder(order));
        } else {
            commonPageParam.addSort(CommonSort.getInstance().setSort("priority").setOrder("ASC"));
            commonPageParam.addSort(CommonSort.getInstance().setSort("create_date").setOrder("DESC"));
        }
        PageResult<TaskView> pageResult = taskService.pageByKeyword(keyword, status, commonPageParam);

        TaskPageResult taskPageResult = new TaskPageResult();
        taskPageResult.setTotal(pageResult.getTotal());
        taskPageResult.setRecords(pageResult.getRecords());

        taskPageResult.setPending(taskService.pageByKeyword(keyword, TaskStatus.PENDING, commonPageParam).getTotal());
        taskPageResult.setRunning(taskService.pageByKeyword(keyword, TaskStatus.RUNNING, commonPageParam).getTotal());
        taskPageResult.setSuccess(taskService.pageByKeyword(keyword, TaskStatus.SUCCESS, commonPageParam).getTotal());
        taskPageResult.setError(taskService.pageByKeyword(keyword, TaskStatus.ERROR, commonPageParam).getTotal());

        return taskPageResult;
    }

    @Override
    public void start(String id) {
        taskService.start(id);
    }

    @Override
    public void complete(String id, TaskStatus status, String stdout) {
        taskService.complete(id, status, stdout);
    }
}
